package com.jiawa.wiki.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiawa.wiki.domain.Ebook;
import com.jiawa.wiki.domain.EbookExample;
import com.jiawa.wiki.mapper.EbookMapper;
import com.jiawa.wiki.req.EbookQueryReq;
import com.jiawa.wiki.req.EbookSaveReq;
import com.jiawa.wiki.resp.EbookQueryResp;
import com.jiawa.wiki.resp.PageResp;
import com.jiawa.wiki.util.CopyUtil;
import com.jiawa.wiki.util.SnowFlake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Description :
 * @Author : YTY
 * @Date : 2021-05-16 11:14
 */
@Service
public class EbookService {

    private static final Logger LOG = LoggerFactory.getLogger(EbookService.class);

    @Resource
    private EbookMapper ebookMapper;

    @Resource
    private SnowFlake snowFlake;

    /**
     * 查询电子书列表
     *
     * @param req
     * @return
     */
    public PageResp<EbookQueryResp> list(EbookQueryReq req) {
        EbookExample ebookExample = new EbookExample();
        // 相当于 sql where条件
        EbookExample.Criteria criteria = ebookExample.createCriteria();
        // 传入名称不为空，才拼接查询条件
        String bookName = req.getName();
        if (!ObjectUtils.isEmpty(bookName)) {
            criteria.andNameLike("%" + bookName + "%");
        }
        // 传入二级分类不为空，才拼接查询条件
        Long categoryId2 = req.getCategoryId2();
        if (!ObjectUtils.isEmpty(categoryId2)) {
            criteria.andCategory2IdEqualTo(categoryId2);
        }

        // PageHelper调用startPage()方法之后，执行的第一个select语句会被分页
        PageHelper.startPage(req.getPage(), req.getSize());
        List<Ebook> ebookList = ebookMapper.selectByExample(ebookExample);

        PageInfo<Ebook> pageInfo = new PageInfo<>(ebookList);
        LOG.info("总行数：{}", pageInfo.getTotal());
        LOG.info("总页数：{}", pageInfo.getPages());

        // 数据脱敏转移，CopyUtil 列表复制
        List<EbookQueryResp> respList = CopyUtil.copyList(ebookList, EbookQueryResp.class);

        PageResp<EbookQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(respList);

        return pageResp;
    }

    /**
     * 保存电子书 -> 新增 OR 更新
     */
    public void save(EbookSaveReq req) {

        // 数据转移
        Ebook ebook = CopyUtil.copy(req, Ebook.class);

        // 主键无数值，新增；主键有数值，更新
        if (ObjectUtils.isEmpty(req.getId())) {
            ebook.setId(snowFlake.nextId());
            ebookMapper.insertSelective(ebook);
        } else {
            ebookMapper.updateByPrimaryKey(ebook);
        }
    }

    /**
     * 删除电子书
     */
    public void delete(Long id) {

        ebookMapper.deleteByPrimaryKey(id);
    }

}
